package com.example.demo.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo.mapper.UsersMapper;
import com.example.demo.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;

@RestController // 用于定义该类为一个RESTful API控制器
@RequestMapping("/chapter03") // 映射路径，所有路径都将以 "/chapter03" 开头
public class UsersController {
    @Autowired
    private UsersMapper usersMapper;
    //获取所有用户
    @GetMapping("/users")
    public List<Users> getAllUsers() {
        return usersMapper.selectList(null);
    }
    //创建新用户
    @PostMapping("/users")
    public Users createUser(@RequestBody Users user) {
        System.out.println(user);
        System.out.println("Received user: " + user);
        try {
            usersMapper.insert(user);
            return user;
        } catch (Exception e) {
            System.err.println("Error creating user: " + e.getMessage());
            e.printStackTrace(); // 打印堆栈信息
            throw e;
        }
    }
    // 更新指定ID的用户
    // 更新指定ID的用户
    @PutMapping("/users/{id}")
    public ResponseEntity<Map<String, Object>> updateUser(@PathVariable Long id, @RequestBody Users updatedUser) {
        Map<String, Object> response = new HashMap<>();
        System.out.println(updatedUser);
        try {
            // 确保更新的用户ID与路径中的ID一致
            updatedUser.setId(id);

            // 校验必要字段
            if (updatedUser.getUserName() == null || updatedUser.getEmail() == null) {
                response.put("success", false);
                response.put("message", "用户名和邮箱不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 执行更新操作
            int result = usersMapper.updateById(updatedUser);
            if (result > 0) {
                response.put("success", true);
                response.put("message", "用户ID【 " + id + " 】更新成功");
                response.put("data", updatedUser);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "用户ID【 " + id + " 】不存在或更新失败");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (Exception e) {
            System.err.println("Error updating user: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    // 禁用指定ID的用户
    @PutMapping("/disable/{id}")
    public String disableUser(@PathVariable Long id) {
        // 创建UpdateWrapper来设置更新条件
        UpdateWrapper<Users> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id); // 条件：ID匹配
        updateWrapper.set("status", "DISABLED"); // 更新status为DISABLED
        // 执行更新操作
        boolean updated = usersMapper.update(null, updateWrapper) > 0;
        // 返回禁用成功的消息
        if (updated) {
            return "用户ID【 " + id + " 】已禁用";
        } else {
            return "禁用用户失败，用户ID【 " + id + " 】不存在或更新失败";
        }
    }
    //删除指定ID的用户
    @DeleteMapping("/users/{id}")
    public String deleteUser(@PathVariable Long id) {
        try {
            int result = usersMapper.deleteById(id); // 根据ID删除用户
            if (result > 0) {
                return "用户ID【 " + id + " 】删除成功";
            } else {
                return "删除用户失败，用户ID【 " + id + " 】不存在";
            }
        } catch (Exception e) {
            System.err.println("Error deleting user: " + e.getMessage());
            e.printStackTrace(); // 打印堆栈信息
            return "删除用户失败，服务器内部错误";
        }
    }
}